<?php

namespace App\Http\Controllers\DingTalk;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use EasyDingTalk\Messages\Text;
use App\Models\DingTalkMessage;
use App\Models\User;
use Illuminate\Support\Facades\URL;

class InterfaceController extends Controller
{
    //
    public function action($action, $name = '')
    {
        $server = app("DT")->$name;
        return $this->$action($server);
    }
    //机器人@消息
    public function robot($server)
    {
        // $robot = $server->robot;
        $server->push(function ($payload) use ($server) {
            return $this->__invoke($payload, $server->app['config']['creator_id'], 'robot', $server->app['config']['app_id']);
        });
        $server->push(function () {
            $text = new Text("获取一条消息");
            return  $text->toJson();
        });
        return $server->serve();
    }
    //服务端消息
    public function server($server)
    {
        $server->push(function ($payload) use ($server) {
            return $this->__invoke($payload, $server->app['config']['creator_id'], 'server', $server->app['config']['app_id']);
        });
        return $server->serve();
    }

    //链接器消息
    public function connect($server)
    {
        return $server->logger->debug("connect", request()->all());
    }

    //第三方扫码登录
    public function oauthqrcode($server)
    {
        if (get("code")) {
            $user = $server->user();
            $this->LoginUserByUnionId($server, $user['user_info']['unionid']);
        } else
            return  $server->withQrConnect()->redirect();
    }
    protected function LoginUserByUnionId($server, $unionid)
    {
        $user = $server->user->getUseridByUnionid($unionid);
        if (!is_null($user = User::where(['userid' => $user['userid']])->first())) {
            \Auth::login($user, false);
            return  redirect("/home");
        }
        return redirect("/login");
    }
    //第三方免登录
    public function oauth($server)
    {
        if (get("code")) {
            $user = $server->user();
            return  $this->LoginUserByUnionId($server, $user['user_info']['unionid']);
        } else
            return  $server->redirect();
    }
    //获取的消息保存下
    public function __invoke($payload, $userid, $action, $app_id)
    {
        // 在此处处理你的业务逻辑
        DingTalkMessage::create(['creator_id' => $userid, 'data' => json_encode($payload), 'action' => 'get', 'kind' => $action, 'app_id' => $app_id]);
        return true;
    }

    public function sendMsg($msg)
    {
    }
}
